package vn.axonactive.vision.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import ch.ivyteam.ivy.environment.EnvironmentNotAvailableException;
import ch.ivyteam.ivy.environment.Ivy;
import ch.ivyteam.ivy.security.IUser;

@ManagedBean(name = "beanUtils")
@RequestScoped
public class BeanUtils {
	
	@SuppressWarnings("unchecked")
	public static <T> T findBean(final String beanName) throws EnvironmentNotAvailableException, Exception {
		T foundBean = Ivy.session().getSecurityContext().executeAsSystemUser(new Callable<T>(){
			public T call() throws Exception {
				 FacesContext context = FacesContext.getCurrentInstance();
				 return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
			}
		});
	    return foundBean;
	}
	
	public static List<IUser> getUsersByRole(final String role) throws EnvironmentNotAvailableException, Exception {
		List<IUser> users = Ivy.session().getSecurityContext().executeAsSystemUser(new Callable<List<IUser>>(){
            public List<IUser> call() throws Exception {
            	return Ivy.session().getSecurityContext().findRole(role).getUsers();
            }

        });
		return users;
	}
	
	public static List<String> filterUsersByQuery(final String filterQuery, final List<IUser> memberList) throws EnvironmentNotAvailableException, Exception {
		List<String> users = Ivy.session().getSecurityContext().executeAsSystemUser(new Callable<List<String>>(){
            public List<String> call() throws Exception {
            	List<String> filteredUsers = new ArrayList<String>();
            	for(int i = 0; i< memberList.size(); i++) {
	        		 IUser member = memberList.get(i);
	        		 if(filterQuery.isEmpty() || member.getEMailAddress().contains(filterQuery)) {
	        			 filteredUsers.add(member.getEMailAddress());
	        		 }
            	}
            	return filteredUsers;
            }

        });
		return users;
	}
	
}
